import React, { useEffect, useRef, useState } from 'react'
import { ProTable } from '@ant-design/pro-components'
import { Button, Popconfirm, Form, Input, Select, App, Switch } from 'antd'
import { useModel } from '@umijs/max'
import { PlusOutlined } from '@ant-design/icons'

export default () => {
  const { GetUserList, DelUser, GetRoles, AddUser, UpdateUser, ChangeStatus } = useModel('UsersList')
  const { platformType, userInfo } = useModel('Global')

  const tableRef = useRef()
  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [pageSize, setPageSize] = useState(10) //  每页数量
  const { message, modal } = App.useApp()
  const [InfoFormRef] = Form.useForm()

  // 新增或者编辑
  const handleAddAndEdit = async (type, row) => {
    console.log('row========', row)
    // 回显数据
    if (type === 'edit') {
      InfoFormRef.setFieldsValue({
        ...row,
        role_id: Number(row.role_id)
      })
    } else {
      InfoFormRef.resetFields()
    }

    const roleList = await GetRoles()

    if (roleList) {
      const typeObj = {
        add: {
          title: '添加账号',
          interface: AddUser,
          msg: '添加成功',
          twoPassword: true,
          pswRequired: true,
          row: {}
        },
        edit: {
          title: '编辑账号',
          interface: UpdateUser,
          msg: '修改成功',
          twoPassword: false,
          pswRequired: false,
          row
        }
      }

      modal.confirm({
        width: 600,
        icon: null,
        title: typeObj[type].title,
        content: (
          <Form preserve={false} form={InfoFormRef} name='user_info' labelCol={{ span: 6 }}>
            <Form.Item name='account' label='账号 : ' rules={[{ required: true, message: '请输入账号' }]}>
              <Input allowClear placeholder='请输入账号' />
            </Form.Item>
            <Form.Item name='real_name' label='姓名/备注 : ' rules={[{ required: true, message: '请输入姓名/备注' }]}>
              <Input allowClear placeholder='请输入姓名/备注' />
            </Form.Item>
            <Form.Item
              name='password'
              label='密码 : '
              rules={[{ required: typeObj[type].pswRequired, message: '请输入密码' }]}
            >
              <Input.Password allowClear placeholder='请输入密码' />
            </Form.Item>

            {typeObj[type].twoPassword ? (
              <Form.Item
                name='re_password'
                label='确认密码 : '
                rules={[
                  { required: true, message: '请输入确认密码' },
                  ({ getFieldValue }) => ({
                    validator(rule, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve()
                      }
                      return Promise.reject('两次密码不一致')
                    }
                  })
                ]}
              >
                <Input.Password allowClear placeholder='二次确认密码' />
              </Form.Item>
            ) : null}

            <Form.Item name='role_id' label='角色 : ' rules={[{ required: true, message: '请选择角色' }]}>
              <Select allowClear placeholder='请选择角色'>
                {roleList.map(item => {
                  return (
                    <Select.Option key={item.id} value={item.id}>
                      {item.role_name}
                    </Select.Option>
                  )
                })}
              </Select>
            </Form.Item>
          </Form>
        ),
        onOk: async () => {
          await InfoFormRef.validateFields()
          const values = InfoFormRef.getFieldsValue()
          let params = {
            ...typeObj[type].row,
            ...values
          }
          const res = await typeObj[type].interface(params)
          if (res) {
            message.success(typeObj[type].msg)
            tableRef.current.reload()
          }
        }
      })
    }
  }

  // 删除
  const handleDelete = async id => {
    const res = await DelUser({ id })
    if (res) {
      message.success('删除成功')
      tableRef.current.reload()
    }
  }

  // 修改状态
  const handleChangeStatus = async row => {
    const { id } = row
    const params = {
      ids: [id],
      type: row.status === 1 ? 3 : 2,
      operate_id: userInfo.id
    }
    const res = await ChangeStatus(params)
    if (res) {
      message.success('修改成功')
      tableRef.current.reload()
    }
  }

  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
      width: 80,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '账号',
      dataIndex: 'account',
      align: 'center'
    },
    {
      title: '姓名/备注',
      dataIndex: 'real_name',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '角色',
      dataIndex: 'role_name',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      render: (_, row) => {
        return (
          <Switch
            onChange={() => handleChangeStatus(row)}
            checkedChildren='开启'
            unCheckedChildren='禁用'
            checked={row.status === 1}
          />
        )
      }
    },
    {
      title: '创建时间',
      dataIndex: 'updated_at',
      align: 'center',
      hideInSearch: true
    },
    {
      title: '最后登录时间',
      dataIndex: 'created_at',
      align: 'center',
      hideInSearch: true
    },

    {
      title: '操作',
      key: 'option',
      width: 150,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return (
          <>
            <Button type='link' key='edit' onClick={() => handleAddAndEdit('edit', row)}>
              编辑
            </Button>
            <Popconfirm
              key='delete'
              title='是否确定将该账号删除？'
              onConfirm={() => handleDelete(row.id)}
              okText='确认'
              cancelText='取消'
            >
              <Button type='link' danger>
                删除
              </Button>
            </Popconfirm>
          </>
        )
      }
    }
  ]

  return (
    <>
      <ProTable
        actionRef={tableRef}
        request={async params => {
          const param = {
            page: params.current,
            page_size: params.pageSize,
            ...params
          }

          setCurrentPage(params.current)
          setPageSize(params.pageSize)

          const res = await GetUserList(param)

          return {
            data: res.data,
            success: true,
            total: res.total
          }
        }}
        pagination={{
          pageSize: pageSize,
          current: currentPage
        }}
        rowKey='id'
        scroll={{ x: 'max-content' }}
        columns={columns}
        headerTitle={
          <Button
            icon={<PlusOutlined />}
            key={Math.random().toString()}
            type='primary'
            onClick={() => handleAddAndEdit('add')}
          >
            添加账号
          </Button>
        }
        search={{
          defaultCollapsed: false,
          labelWidth: 80,
          span: 6
        }}
      />
    </>
  )
}
